package ink.sunflowerk.utils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;

public class CheckImage {
    public static void getYzm(HttpServletResponse resp, HttpServletRequest req) throws Exception {
        String message = "3456789abcdefghjkmnpqstuvwxy";
        //1 在内存中开辟空间 用于画画
        BufferedImage bin = new BufferedImage(150, 33, BufferedImage.TYPE_INT_RGB);
        //2 获取画笔
        Graphics2D g = (Graphics2D) bin.getGraphics();
        //3 涂染料 画背景
        g.setColor(Color.WHITE);
        //4 画背景:长方形
        g.fillRect(2, 2, 145, 30);
        //5 画主题
        //随机四五个字符
        String str = "";
        for (int i = 0; i < 4; i++) {
            str += message.charAt((int) (Math.random() * message.length()));
        }
        //给字符设置文字样式
        Font font = new Font(null, Font.BOLD, 28);
        g.setFont(font);
        //把字符串中的所有字符画到画布上
        for (int i = 0; i < str.length(); i++) {
            //笔蘸墨
            g.setColor(new Color((int) (Math.random() * 100 + 120), (int) (Math.random() * 100 + 120), (int) (Math.random() * 100 + 120)));
            //写字
            g.drawString(str.charAt(i) + "", i * 35 + 10, 28);
        }
        //画干扰线
        for (int i = 0; i < (int) (Math.random() * 5 + 5); i++) {
            g.setColor(new Color((int) (Math.random() * 50 + 120), (int) (Math.random() * 50 + 120), (int) (Math.random() * 50 + 120)));
            g.drawLine(2, (int) (Math.random() * 33 + 2), 145, (int) (Math.random() * 33 + 2));
        }
        //把验证码的信息装入session
        System.out.println("验证码：==》"+str);
        req.getSession().setAttribute("yzmSession", str);
        //把内存中图片的信息通过response的输出流 响应给客户端
        ImageIO.write(bin, "JPEG", resp.getOutputStream());
    }
}